package com.luoran.bartalks.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * @author chenhao
 * @date ${date}
 */
public class ImagesUtil {

    private static final Logger log = LoggerFactory.getLogger(ImagesUtil.class);
    private static String actionPath = "";

    /**
     * 获取上传图片后的路径
     *
     * @param req
     * @param imagePath 自定义图片上传路径
     * @return
     */
    public static String getImageUrlByLast(MultipartHttpServletRequest req, String imagePath) {
        String url = uploadImageByCustom(req, imagePath);
        if (StringUtils.isBlank(url)) {
            return url;
        }
        // String[] split = url.split("\\\\");
        // return split.length < 1 ? url : actionPath + split[split.length - 1];
        return actionPath + url.substring(url.lastIndexOf("/") + 1);
    }

    /**
     * 上传图片
     *
     * @param req
     * @param imagePath 自定义图片上传路径
     * @return 图片url
     */
    public static String uploadImage(MultipartHttpServletRequest req, String imagePath) {
        return uploadImageByCustom(req, imagePath);
    }

    /**
     * 访问图片
     *
     * @rep
     * @fileName 图片名称
     * @imagePath 自定义访问图片路径
     */
    public static void getImage(HttpServletResponse rep, String fileName, String imagePath) {
        getImage(rep, getImageFile(fileName, imagePath));
    }

    private static String uploadImageByCustom(MultipartHttpServletRequest req, String imagePath) {
        String filePath = null;
        for (Iterator<String> it = req.getFileNames(); it.hasNext();) {
            String fname = it.next();
            if (StringUtils.isNotBlank(fname)) {
                MultipartFile mulFile = req.getFile(fname);
                String file = mulFile.getOriginalFilename();
                String fileName = file.substring(file.lastIndexOf("\\") + 1);// 为兼容IE8
                filePath = getImageUrl(fileName, imagePath);
                File output = new File(filePath);
                InputStream input = null;
                FileOutputStream fileOutput = null;
                try {
                    input = mulFile.getInputStream();
                    fileOutput = new FileOutputStream(output);
                    IOUtils.copy(input, fileOutput);
                } catch (IOException e) {
                    log.error(e.getMessage());
                } finally {
                    if (input != null) {
                        try {
                            input.close();
                        } catch (IOException e) {
                        }
                    }
                    if (fileOutput != null) {
                        try {
                            fileOutput.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        }
        return filePath;
    }

    private static void getImage(HttpServletResponse rep, File file) {
        if (file == null || !file.exists() || !isImage(file.getName())) {
            log.error("file等于Null, 或不是一张图片, 或找不到该图片");
            return;
        }
        rep.setContentType(getImgContentType(file.getName()));
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            IOUtils.copy(fis, rep.getOutputStream());
            rep.flushBuffer();
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    log.error("fis文件流关闭失败！");
                }
            }
        }
    }

    public static File getImageFile(String fileName, String imagePath) {
        if (!isImage(fileName)) {
            String[] suffixs = { ".jpg", ".png", ".jpeg" };
            File file = null;
            for (String suffix : suffixs) {
                file = new File(getImagePath(fileName + suffix, imagePath));
                if (file.exists()) {
                    return file;
                }
            }
        }
        return new File(getImagePath(fileName, imagePath));
    }

    public static String getImagePath(String fileName, String imagePath) {
        return imagePath + File.separator + fileName;
    }

    public static String getImageUrl(String fileName, String imagePath) {
        // return imagePath + File.separator + UUID.shortString() + "-" + fileName;
        return imagePath + "/" + UUID.shortString() + "-" + fileName;
    }

    public static boolean isImage(String name) {
        name = name.toLowerCase();
        return name.endsWith(".jpg") || name.endsWith(".png") || name.endsWith(".gif") || name.endsWith(".bmp")
                || name.endsWith("jpeg");
    }

    public static String getImgContentType(String fname) {
        if (fname.endsWith(".jpg") || fname.endsWith(".jpeg")) {
            return "image/jpeg;charset=utf-8";
        } else if (fname.endsWith(".png")) {
            return "image/png;charset=utf-8";
        } else if (fname.endsWith(".gif")) {
            return "image/gif;charset=utf-8";
        }
        return null;
    }

}
